package io.kiki.sba.registry.client.task;

import io.kiki.sba.registry.client.api.Register;
import lombok.Getter;
import lombok.Setter;

@Setter
@Getter
public class TaskEvent implements Comparable<TaskEvent> {
    private static final int MAX_DELAY_TIME = 1000;

    private Register source;

    private int sendCount;

    private long triggerTime;


    public TaskEvent(Register source) {
        this.source = source;
        this.triggerTime = System.currentTimeMillis();
        this.sendCount = 0;
    }


    public long delayTime() {
        int time = sendCount * 200;
        if (time > MAX_DELAY_TIME) {
            time = MAX_DELAY_TIME;
        }
        return time - (System.currentTimeMillis() - this.triggerTime);
    }


    @Override
    public int compareTo(TaskEvent taskEvent) {
        if (this.sendCount > taskEvent.sendCount) {
            return 1;
        } else
            if (this.sendCount < taskEvent.sendCount) {
                return -1;
            }
        Register register1 = source;
        Register register2 = taskEvent.getSource();

        if (register1 == null) {
            return register2 != null ? -1 : 0;
        } else {
            if (register2 == null) {
                return 1;
            }
        }

        long t1 = register1.getTimestamp();
        long t2 = register2.getTimestamp();
        if (t1 > t2) {
            return 1;
        } else
            if (t1 < t2) {
                return -1;
            }
        return 0;
    }


    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (!(o instanceof TaskEvent)) {
            return false;
        }

        TaskEvent taskEvent = (TaskEvent) o;

        if (sendCount != taskEvent.sendCount) {
            return false;
        }
        if (triggerTime != taskEvent.triggerTime) {
            return false;
        }
        return source != null ? source.equals(taskEvent.source) : taskEvent.source == null;
    }


    @Override
    public int hashCode() {
        int result = source != null ? source.hashCode() : 0;
        result = 31 * result + sendCount;
        result = 31 * result + (int) (triggerTime ^ (triggerTime >>> 32));
        return result;
    }


    public int incSendCount() {
        return this.sendCount++;
    }
}
